package cs340.stormtroopers.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

import cs340.stormtroopers.hypeerweb.Node;

public class SurrogateNeighborDelegate extends NeighborDelegate
{
	public SurrogateNeighborDelegate(Node original, Node delegate)
	{
		super(original, delegate);
	}

	@Override
	public void insertIntoDatabase(Connection connection) throws SQLException,
			IOException, ClassNotFoundException
	{
		PreparedStatement insertSurrogateNeighborStatement = connection
				.prepareStatement("INSERT INTO SurrogateNeighbor(Top, Bottom) VALUES (?, ?)");

		insertSurrogateNeighborStatement.setInt(1, originalNode.getWebIdValue());
		insertSurrogateNeighborStatement.setInt(2, delegate.getWebIdValue());
		insertSurrogateNeighborStatement.addBatch();
		
		connection.setAutoCommit(false);
		insertSurrogateNeighborStatement.executeBatch();
		connection.setAutoCommit(true);
		insertSurrogateNeighborStatement.close();
	}

	public static Iterator<Delegate> wrap(final Node original, final Iterable<Node> nodes)
	{
		return new Iterator<Delegate>() {
			private Iterator<Node> iterator = nodes.iterator();
			@Override
			public boolean hasNext()
			{
				return iterator.hasNext();
			}

			@Override
			public Delegate next()
			{
				return new SurrogateNeighborDelegate(original, iterator.next());
			}

			@Override
			public void remove()
			{
				throw new UnsupportedOperationException();
			}
			
		};
	}
}
